/**
 * @author kanglang
 * @createDate 2020/8/24
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2020-02-05  12:02:52
 * @description 我的/个人中心
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  SafeAreaView,
  TouchableOpacity,
  ImageBackground
} from 'react-native';
import { iconUserCoffee, iconUserGray, leftBack } from '../../../../image';
import { msg, Header, _ } from '../../../../common';
import { isAndroid, px2dp } from '../../../../common/styles';
import RowItem from '../../../../components/SimpleRowItem';
import api from '../../../../api';
import supply from '../../../../api/supply';
import Picker from '../../../../common/picker';

export default class User extends React.Component {
  static navigationOptions = () => ({
    title: '我的',
    tabBarIcon: ({ focused }) => (
      <Image source={focused ? iconUserCoffee : iconUserGray} style={{ width: 24, height: 24 }} />
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      custId: '', // 个人客户id
      cargoOwnerInfo: {
        avatarId: require('../../../../image/icons/defaultman.png'),
        name: '',
        consignorType: null, // 货主类型
        custName: null, // 企业名字
        custType: null, // 货主类型
      },
      selectData: {
        custId: '', // 若选择企业则为企业id，若选择个人则为个人id
        custName: null, // 企业名字
        custType: null, // 客户类型
        consignorType: null, // 货主类型
      },
      consignorTypeDataList: [], // 所有货主类型
      custIdDataList: [], // 所有企业
    };
  }

  componentDidMount() {
    this.getUserInfo();
    this.saveOrGetConsignorRedis();
    this.allConsignorType();
  }

  render() {
    const { cargoOwnerInfo } = this.state;
    return (
      <SafeAreaView style={styles.safeViewStyle}>
        <View style={styles.container}>
          <ImageBackground
            style={styles.bgStyle}
            source={require('../../../../image/icons/shipper_head_bg.png')}
            resizeMode='stretch'
          >
            <Header
              style={styles.headerStyle}
              renderLeft={() => {
                return (
                  <TouchableOpacity
                    activeOpacity={0.8}
                    style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
                      { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
                    onPress={() => {
                      msg.emit('router: back');
                    }}
                  >
                    <Image
                      style={[styles.backImg]}
                      source={leftBack}
                      resizeMode='stretch'
                    />
                  </TouchableOpacity>
                );
              }}
            />
            <Image
              style={styles.shipperAvartar}
              source={cargoOwnerInfo.avatarId}
            />
          </ImageBackground>
          <View style={styles.boxWrap}>
            <View style={styles.certWrap}>
              <Text style={styles.shipperName}>{cargoOwnerInfo.name}</Text>
              <TouchableOpacity
                style={styles.certFlagOne}
                onPress={() => {
                  this.getCustomLegals();
                }}
              >
                <Image style={styles.certIcon} source={require('../../../../image/icons/icon_wl_modify.png')} />
                {/* <Text style={styles.certTip}>已认证</Text> */}
              </TouchableOpacity>
            </View>

            <View style={styles.mt40}>
              {/* <RowItem */}
              {/*  leftStyle={styles.pl0} */}
              {/*  rightStyle={styles.mr0} */}
              {/*  title="发货历史" */}
              {/*  icon={require('../../../../image/icons/icon_history.png')} */}
              {/*  onPress={this.sendHistory} */}
              {/* /> */}
              {/* <RowItem */}
              {/*  leftStyle={styles.pl0} */}
              {/*  rightStyle={styles.mr0} */}
              {/*  title="货源收藏" */}
              {/*  icon={require('../../../../image/icons/icon_favorites.png')} */}
              {/*  onPress={this.myFavorites} */}
              {/* /> */}
              <RowItem
                leftStyle={styles.pl0}
                rightStyle={styles.mr0}
                title='货主类型'
                icon={require('../../../../image/icons/icon_consignor.png')}
                showArrow={false}
                titleRight={this.translateConsignorType(cargoOwnerInfo.consignorType)}
              />
              {
                cargoOwnerInfo.custType === 2 && (
                  <RowItem
                    leftStyle={styles.pl0}
                    rightStyle={styles.mr0}
                    title='企业信息'
                    icon={require('../../../../image/icons/icon_enterprise.png')}
                    showArrow={false}
                    titleRight={cargoOwnerInfo.custName}
                  />
                )
              }
              <RowItem
                style={styles.lastRowStyle}
                leftStyle={{ paddingLeft: 0 }}
                rightStyle={{ marginRight: 0 }}
                title='货物运输协议'
                icon={require('../../../../image/icons/icon_protocol.png')}
                onPress={this.wlProtocal}
              />
            </View>
          </View>
        </View>
      </SafeAreaView>
    );
  }

  sendHistory = () => {
    msg.emit('router: goToNext', { routeName: 'SendHistory' });
  }

  myFavorites = () => {
    msg.emit('router: goToNext', { routeName: 'ShipperFavorites' });
  }

  wlProtocal = () => {
    msg.emit('router: goToNext', {
      routeName: 'CustAgreement',
      routerFrom: 'logiticsAgreement'
    });
  }

  // 货主类型翻译
  translateConsignorType = (type) => {
    const { consignorTypeDataList } = this.state;
    let consignor = consignorTypeDataList.filter(consignor => consignor.code === type);
    if (consignor.length !== 0) {
      return consignor[0].name;
    }
    return '';
  }

  /**
   *
   * @param title 选择框标题
   * @param dataList  选择框数据源
   * @param pickerType  选择类型 1 客户类型 2 企业 3 货主类型
   */
  showPicker = (title, pickerType) => {
    const { consignorTypeDataList, custIdDataList } = this.state;
    let dataList = {
      1: ['个人', '企业'],
      2: custIdDataList.map(item => item.custName),
      3: consignorTypeDataList.map(item => item.name),
    };
    Picker.init({
      pickerTitleText: title,
      pickerCancelBtnText: '取消',
      pickerConfirmBtnColor: [186, 145, 74, 1],
      pickerCancelBtnColor: [102, 101, 100, 1],
      pickerConfirmBtnText: '确定',
      selectedValue: [],
      pickerBg: [255, 255, 255, 1],
      pickerToolBarBg: [255, 255, 255, 1],
      pickerFontColor: [186, 145, 74, 1],
      pickerRowHeight: 40,
      pickerData: dataList[pickerType],
      onPickerConfirm: (pickedValue, pickedIndex) => { // 确定
        switch (pickerType) {
        case 1:
          this.selectCustType(pickedValue[0]);
          break;
        case 2:
          this.selectCustName(pickedValue[0]);
          break;
        case 3:
          this.selectConsignorType(pickedValue[0]);
          break;
        }
      },
      onPickerCancel: (pickedValue, pickedIndex) => { // 取消
        Picker.hide();
      },
      onPickerSelect: (pickedValue, pickedIndex) => { // 选择

      },
    });
    Picker.show();
  };

  // 选择客户类型
  selectCustType = (type) => {
    const { custId, selectData } = this.state;
    let newSelectData;
    if (type === '个人') {
      newSelectData = {
        custId,
        custName: '',
        custType: 1,
      };
      this.setState({ selectData: { ...selectData, ...newSelectData } }, () => {
        this.showPicker('货主类型', 3);
      });
    } else if (type === '企业') {
      newSelectData = {
        custType: 2,
      };
      this.setState({ selectData: { ...selectData, ...newSelectData } }, () => {
        this.showPicker('选择企业', 2);
      });
    }
  }

  // 选择企业
  selectCustName = (type) => {
    const { selectData, custIdDataList } = this.state;
    let custNameData = custIdDataList.filter(custIdData => custIdData.custName === type);
    const { custId, custName } = custNameData[0];
    this.setState({ selectData: { ...selectData, custId, custName } }, () => {
      this.showPicker('货主类型', 3);
    });
  }

  // 选择货主类型
  selectConsignorType = (type) => {
    const { selectData, consignorTypeDataList } = this.state;
    let consignorData = consignorTypeDataList.filter(consignor => consignor.name === type);
    const { code } = consignorData[0];
    this.setState({ selectData: { ...selectData, consignorType: code } }, () => {
      const { selectData } = this.state;
      supply.saveOrGetConsignorRedis(selectData).then(res => {
        if (res.success) {
          this.saveOrGetConsignorRedis();
          msg.emit('app:tip', { text: '修改成功!' });
        } else {
          msg.emit('app:tip', { text: '修改失败!' });
        }
      });
    });
  }

  /**
   * 接口调用
   */
  // 获取客户类型信息
  saveOrGetConsignorRedis = () => {
    supply.saveOrGetConsignorRedis({}).then(res => {
      if (res.success) {
        const { cargoOwnerInfo } = this.state;
        let newCargoOwnerInfo = {

          ...cargoOwnerInfo,
          custType: res.data.custType, // 客户类型
          custName: res.data.custName,
          consignorType: res.data.consignorType // 货主类型

        };
        this.setState({ cargoOwnerInfo: newCargoOwnerInfo });
      } else {
        msg.emit('app:tip', { text: '获取信息失败' });
        msg.emit('router: back');
      }
    });
  }

  // 获取所有货主类型
  allConsignorType = () => {
    supply.allConsignorType().then(res => {
      if (res.success) {
        this.setState({ consignorTypeDataList: res.data });
      }
    });
  }

  // 获取用户信息
  getUserInfo = () => {
    api.user.getUserInfo().then(res => {
      if (res.success && res.data) {
        const { cargoOwnerInfo } = this.state;
        let newCargoOwnerInfo = {

          ...cargoOwnerInfo,
          avatarId: res.data.avatarId ? { uri: res.data.avatarId } : require('../../../../image/icons/defaultman.png'),
          name: res.data.name,
        };
        this.setState({ cargoOwnerInfo: newCargoOwnerInfo, custId: res.data.custId });
      } else {
        msg.emit('app:tip', { text: '获取信息失败' });
      }
    });
  }

  // 查询公司列表 如果为空，默认个人
  getCustomLegals = () => {
    supply.getCustomLegals().then(res => {
      if (res.success) {
        if (res.data === null) { // 个人用户
          const { selectData, custId } = this.state;
          let newSelectData = { ...selectData,
            custId,
            custType: 1,
            custName: '',
          };
          this.setState({ selectData: newSelectData }, () => {
            this.showPicker('货主类型', 3);
          });
        } else { // 企业用户
          this.setState({ custIdDataList: res.data }, () => {
            this.showPicker('选择客户类型', 1);
          });
        }
      } else {
        msg.emit('app:tip', { text: '获取信息失败' });
      }
    });
  }
}

const styles = StyleSheet.create({
  safeViewStyle: {
    backgroundColor: '#fff',
  },
  container: {
    height: '100%',
    width: '100%',
    backgroundColor: '#fff',
  },
  bgStyle: {
    width: '100%',
    height: px2dp(190) * 2
  },
  headerStyle: {
    backgroundColor: 'rgba(0,0,0,0)',
    borderColor: 'rgba(0,0,0,0)',
    ..._.ifIphoneX({ top: 10 }, { top: 0 }),
  },
  backImg: {
    width: px2dp(36),
    height: px2dp(36),
    marginLeft: isAndroid ? 0 : px2dp(34),
  },
  RowItemStyle: {
    paddingLeft: 0
  },
  lastRowStyle: {
    borderBottomLeftRadius: px2dp(10) * 2,
    borderBottomRightRadius: px2dp(10) * 2
  },
  shipperAvartar: {
    width: px2dp(135),
    height: px2dp(135),
    top: px2dp(70) * 2,
    borderRadius: px2dp(135) * 2,
    marginLeft: px2dp(16) * 2,
    borderColor: '#F5F5F5',
    borderWidth: px2dp(13)
  },
  boxWrap: {
    paddingTop: px2dp(12) * 2,
    paddingLeft: px2dp(16) * 2,
    paddingRight: px2dp(16) * 2,
    paddingBottom: px2dp(12) * 2
  },
  certWrap: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  shipperName: {
    color: '#343332',
    fontSize: px2dp(21) * 2
  },
  certFlag: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: px2dp(12) * 2,
    backgroundColor: '#E9F8E9',
    paddingLeft: px2dp(8) * 2,
    paddingTop: px2dp(5),
    paddingRight: px2dp(8) * 2,
    paddingBottom: px2dp(5),
    borderRadius: px2dp(14) * 2
  },
  certFlagOne: {
    height: px2dp(48),
    width: px2dp(48),
    borderRadius: px2dp(24),
    backgroundColor: '#F0EFEF',
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: px2dp(20)
  },
  certIcon: {
    width: px2dp(12) * 2,
    height: px2dp(12) * 2
  },
  certTip: {
    color: '#2CBD26',
    fontSize: px2dp(11) * 2,
    marginLeft: px2dp(4) * 2
  },
  pl0: {
    paddingLeft: 0
  },
  mr0: {
    marginRight: 0
  },
  mt40: {
    marginTop: 40
  }
});
